<script setup="" lang="ts">
import { orderStateList, OrderState } from '@/services/constants'
import { getMemberOrderAPI, reviewAPI, takeGoodsAPI } from '@/services/order'
import { wxPayAPI } from '@/services/wxPay'
import { useMemberStore } from '@/stores'
import type { OrderListParams, OrderResult } from '@/types/order'
import { onMounted, ref } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
//获取会员信息
const { id } = useMemberStore().profile
//定义props接收参数
const props = defineProps<{
  orderState: number //订单状态
}>()
//定义请求参数
const queryParams: OrderListParams = {
  currPageNo: 1,
  pageSize: 5,
  orderState: props.orderState,
  userId: id,
}

let totalPageCount = ref(0) //总页数
let end = ref(false) //是否已到底部

//获取订单列表
const orderList = ref<OrderResult[]>([])
const getOrderList = async () => {
  const res = await getMemberOrderAPI(queryParams)
  orderList.value = res.result.list
  totalPageCount.value = res.result.totalPageCount
}

//滚动到底部加载更多
const onScrolltolower = async () => {
  queryParams.currPageNo++
  //页码大于总页码，说明没有更多数据
  if (queryParams.currPageNo >= totalPageCount.value) {
    end.value = true
    return uni.showToast({
      title: '没有数据了',
      icon: 'none',
    })
  }
  //获取订单列表
  const res = await getMemberOrderAPI(queryParams)
  orderList.value.push(...res.result.list)
}

//定义订单支付方法
const orderPay = async (orderId: number) => {
  //获取会员id
  const userId = useMemberStore().profile.id
  //构建请求参数
  const data = {
    userId,
    orderId,
    opr: 'prepay',
  }
  //发起支付请求
  const res = await wxPayAPI(data)
  console.log(res)
  if (res.code != 200) {
    return uni.showToast({
      title: '支付失败',
      icon: 'error',
    })
  }
  //调用微信支付接口
  await wx.requestPayment({
    timeStamp: res.result.timeStamp,
    nonceStr: res.result.nonceStr,
    package: res.result.package,
    signType: 'MD5',
    paySign: res.result.paySign,
    success: (res) => {
      //关闭当前页面，跳转支付结果页面
      uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${orderId}` })
    },
    fail: (res) => {},
  })
}
const takeGoods = (orderId: number) => {
  uni.showModal({
    title: '提示',
    content: '',
    confirmText: '确认收货',
    cancelText: '取消',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        const res = await takeGoodsAPI(orderId)
        if (res.code === 200) {
          uni.showToast({
            title: '收货成功',
            icon: 'success',
          })
        } else {
          uni.showToast({
            title: '收货失败',
            icon: 'error',
          })
        }
        emit('parentMethod')
      }
    },
    fail: () => {},
  })
}

onMounted(() => {
  getOrderList()
})

defineExpose({
  getOrderList,
})

const emit = defineEmits<{ (event: 'parentMethod'): void }>()
const evaluateOrder = ref<OrderResult>()
// 打开评价功能
const openEvaluate = async (order: OrderResult) => {
  showEvaluate.value = true
  evaluateOrder.value = order
}
// 评价功能区域
// 评价
const content = ref<string>('')
// 是否展示评价区域
const showEvaluate = ref<boolean>(false)
// 评分
const score = ref<number>(0)
const selectStar = (scores: number) => (score.value = scores)
// 评分图片链接
const starActive = ref<string>(
  'https://ly-xuan.oss-cn-guangzhou.aliyuncs.com/2025-06-04/1749020870994.png',
)
const starInactive = ref<string>(
  'https://ly-xuan.oss-cn-guangzhou.aliyuncs.com/2025-06-04/1749020897311.png',
)
// 关闭评分
const closeEvaluate = () => {
  showEvaluate.value = false
}
const submitEvaluate = async () => {
  if (evaluateOrder.value) {
    const res = await reviewAPI(evaluateOrder.value.id)
    if (res.code != 200) {
      uni.showToast({ title: '评价失败', icon: 'error' })
    } else {
      uni.showToast({ title: '评价成功', icon: 'success' })
    }
    getOrderList()
    showEvaluate.value = false
    evaluateOrder.value = undefined
    score.value = 0
    content.value = ''
  }
}
</script>
<template>
  <!-- 订单列表 -->
  <scroll-view scroll-y class="orders" @scrolltolower="onScrolltolower">
    <view class="card" v-for="item in orderList" :key="item.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ item.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[item.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text v-if="item.orderState >= OrderState.PendingReview" class="icon-delete"></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="goods in item.goods"
        :key="goods.goodsId"
        class="goods"
        :url="`/pagesOrder/detail/detail?id=${item.id}`"
        hover-class="none"
      >
        <view class="cover">
          <img mode="aspectFit" :src="goods.picture" />
        </view>
        <view class="meta">
          <view class="name ellipsis">{{ goods.name }}</view>
          <view class="type">{{ goods.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ item.actualPrice }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="item.orderState === OrderState.PendingPayment">
          <view class="button primary" @tap="orderPay(item.id)">去支付</view>
        </template>
        <template v-else-if="item.orderState === OrderState.PendingDelivery">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
        </template>
        <template v-else-if="item.orderState === OrderState.PendingGoods">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <view class="button primary" @tap="takeGoods(item.id)">确认收货</view>
        </template>
        <template v-else-if="item.orderState === OrderState.PendingReview">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <view class="button primary" @tap="openEvaluate(item)">立即评价</view>
        </template>
        <template v-else-if="item.orderState === OrderState.Completed">
          <navigator
            class="button secondary"
            :url="`/pagesOrder/create/create?orderId=${item.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <view class="button primary">退换货/售后</view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view class="loading-text" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      {{ end ? '没有更多数据~' : '正在加载...' }}
    </view>
    <!-- 评价弹窗 -->
    <view class="evaluate-mask" v-if="showEvaluate" @click="closeEvaluate">
      <view class="evaluate-box" @click.stop>
        <view class="evaluate-title">商品评价</view>

        <view class="star-container">
          <view class="star-text">请对商品进行评分：</view>
          <view class="star-list">
            <image
              v-for="(item, index) in 5"
              :key="index"
              :src="index < score ? starActive : starInactive"
              mode="aspectFit"
              @click="selectStar(index + 1)"
              class="star-item"
            ></image>
          </view>
        </view>

        <view class="content-container">
          <textarea
            v-model="content"
            placeholder="请输入您的评价内容..."
            maxlength="200"
            class="content-textarea"
          ></textarea>
          <view class="content-count">{{ content.length }}/200</view>
        </view>

        <view class="btn-container">
          <button type="default" @click="closeEvaluate">取消</button>
          <button type="primary" @click="submitEvaluate">提交评价</button>
        </view>
      </view>
    </view>
  </scroll-view>
</template>
<style scoped>
.evaluate-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.evaluate-box {
  width: 80%;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
}

.evaluate-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.star-container {
  margin-bottom: 20px;
}

.star-text {
  margin-bottom: 10px;
}

.star-list {
  display: flex;
  margin-bottom: 10px;
}

.star-item {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.star-desc {
  color: #999;
  font-size: 14px;
}

.content-container {
  margin-bottom: 20px;
}

.content-textarea {
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px;
  height: 100px;
}

.content-count {
  text-align: right;
  color: #999;
  font-size: 14px;
  margin-top: 5px;
}

.upload-container {
  margin-bottom: 20px;
}

.upload-text {
  margin-bottom: 10px;
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
}

.upload-item {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;
}

.upload-item image {
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

.delete-btn {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 18px;
  height: 18px;
  background-color: #ff4544;
  color: #fff;
  border-radius: 50%;
  text-align: center;
  line-height: 18px;
  font-size: 12px;
}

.upload-btn {
  width: 60px;
  height: 60px;
  border: 1px dashed #ddd;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-btn image {
  width: 30px;
  height: 30px;
}

.btn-container {
  display: flex;
  justify-content: space-between;
}

.btn-container button {
  width: 48%;
}
</style>
